package org.i1510.common.utils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

import org.i1510.common.po.SysRole;
import org.i1510.common.po.SysUser;

public class BeanUtils {
	/**
	 * @author Kenshinbo
	 * @描述：map拷贝到javabean
	 * @param map
	 * @param o
	 * @version BeanUtils.java,v 1.1 Aug 7, 2010 9:58:02 AM BOBO-L-NEAR
	 */
	public static void mapCopyObject(Map<String, Object> map, Object o) {
		Method[] methods = o.getClass().getMethods();
		for (String key : map.keySet()) {
			String methodstr = "set" + key.substring(0, 1).toUpperCase()
					+ key.substring(1);
			for (Method method : methods) {
				if (method.getName().equals(methodstr)) {
					try {
						method.invoke(o, new Object[] { map.get(key) });
					} catch (IllegalArgumentException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (InvocationTargetException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}

		}
	}

	/**
	 * @author Kenshinbo
	 * @描述： javabean拷贝到map
	 * @param o
	 * @param map
	 * @version BeanUtils.java,v 1.1 Aug 7, 2010 9:58:20 AM BOBO-L-NEAR
	 */
	public static void ObjectCopyMap(Object o, Map<String, Object> map) {
		if (null == o) {
			o = new Object();
		}
		Method[] methods = o.getClass().getMethods();
		for (int i = 0; i < methods.length; i++) {
			Method method = (Method) methods[i];
			if (method.getName().startsWith("get")) {
				String prop = method.getName().substring(3, 4).toLowerCase()
						+ method.getName().substring(4);
				Object obj = null;
				try {
					obj = method.invoke(o, null);
					map.put(prop, obj);

				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

		}
	}

	/**
	 * @author Kenshinbo
	 * @描述：用于字符串第一个字符转成小写(主要用于转化get，set方法)
	 * @param str
	 * @return
	 * @version CommonUtils.java,v 1.1 Aug 7, 2010 10:07:05 AM BOBO-L-NEAR
	 */
	public static String firstCharToLowCase(String str) {
		if (str == null) {
			return null;
		}
		if (str.trim().equals("")) {
			return "";
		}
		char firstChar = str.charAt(0);
		String tempStr = new String(new char[] { firstChar }).toLowerCase();
		if (str.length() > 1) {
			return tempStr + str.substring(1);
		} else {
			return tempStr;
		}
	}

	/**
	 * @author Kenshinbo
	 * @描述：用于字符串第一个字符转成大写(主要用于转化get，set方法)
	 * @param str
	 * @return
	 * @version CommonUtils.java,v 1.1 Aug 7, 2010 10:07:44 AM BOBO-L-NEAR
	 */
	public static String firstCharToUpperCase(String str) {
		if (str == null) {
			return null;
		}
		if (str.trim().equals("")) {
			return "";
		}
		char firstChar = str.charAt(0);
		String tempStr = new String(new char[] { firstChar }).toUpperCase();
		if (str.length() > 1) {
			return tempStr + str.substring(1);
		} else {
			return tempStr;
		}
	}

	/**
	 * @author Kenshinbo
	 * @描述： 将target的属性值赋给source相同的属性，并且这些要复制的属性由list指定
	 * @param target
	 * @param source
	 * @param list
	 *            如果list为空则全部一对一赋值,不为空则复制指定属性
	 * @version CommonUtils.java,v 1.1 Aug 7, 2010 10:04:35 AM BOBO-L-NEAR
	 */
	public static void copyPropertiesInList(Object target, Object source,
			List list) {
		if (list == null) {
			try {
				org.apache.commons.beanutils.BeanUtils.copyProperties(target,
						source);
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
		} else {
			Class clazz = source.getClass();
			Class targetClass = target.getClass();
			Field[] fields = clazz.getDeclaredFields();
			for (int i = 0; i < fields.length; i++) {
				Field field = fields[i];
				if (field.getName().equals("serialVersionUID")) {
					continue;
				}
				if (list.contains(field.getName())) {
					try {
						Method getMethod = clazz.getMethod(
								"get"
										+ BeanUtils.firstCharToUpperCase(field
												.getName()), null);
						Method setMethod = targetClass.getMethod(
								"set"
										+ BeanUtils.firstCharToUpperCase(field
												.getName()),
								new Class[] { getMethod.getReturnType() });
						if (setMethod != null) {
							setMethod.invoke(target, new Object[] { getMethod
									.invoke(source, null) });
						}
					} catch (SecurityException e) {
						e.printStackTrace();
					} catch (NoSuchMethodException e) {
						e.printStackTrace();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}

	}

	/**
	 * 获取当前类声明的private/protected变量
	 */
	static public Object getFieldValue(Object object, String propertyName)
			throws IllegalAccessException, NoSuchFieldException {
		Field field = object.getClass().getDeclaredField(propertyName);
		field.setAccessible(true);

		return field.get(object);
	}

	/**
	 * 因为getFieldValue()方法，无法读取super class的属性的值； 所以本方法做出扩展，允许读取super class的属性的值；
	 * 
	 * @param object
	 * @param propertyName
	 * @return
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public static Object getFieldValueInAllSuper(Object object,
			String propertyName) throws IllegalAccessException,
			NoSuchFieldException {
		Class claszz = object.getClass();
		Field field = null;

		do {
			try {
				field = claszz.getDeclaredField(propertyName);
			} catch (NoSuchFieldException e) {
				// e.printStackTrace();
				field = null;
			}
			claszz = claszz.getSuperclass();
		} while (field == null && claszz != null);

		if (field == null)
			return null;

		field.setAccessible(true);
		return field.get(object);
	}

	public static void main(String[] args) {
		// SysUser destSysUser = new SysUser();
		// destSysUser.setFdId("11");
		// destSysUser.setFdName("destshow");
		// destSysUser.setFdEmail("destemail");
		//
		// SysUser srcSysUser = new SysUser();
		// srcSysUser.setFdId("11");
		// srcSysUser.setFdName("srcshow");
		// // srcSysUser.setFdEmail("srcemail");
		//
		// BeanUtils.copy(destSysUser, srcSysUser);
		// System.out.println("-类SysUser同步成功!==name:"+destSysUser.getFdName()+"==email:"+destSysUser.getFdEmail());
		//
		// SysUser destSysUser1 = new SysUser();
		// destSysUser1.setFdId("11");
		// destSysUser1.setFdName("destshow");
		// destSysUser1.setFdEmail("destemail");
		//
		// SysUser srcSysUser1 = new SysUser();
		// srcSysUser1.setFdId("11");
		// srcSysUser1.setFdName("srcshow");
		// srcSysUser1.setFdEmail("srcemail");
		// BeanUtils.copy(srcSysUser1,destSysUser1);
		// System.out.println("-类SysUser同步成功!==name:"+srcSysUser1.getFdName()+"==email:"+srcSysUser1.getFdEmail());

//		SysUser destSysUser2 = new SysUser();
//		destSysUser2.setFdId("11");
//		destSysUser2.setFdName("destshow");
//		destSysUser2.setFdEmail("destemail");
//
//		SysRole sysRole = new SysRole();
//		sysRole.setFdId("123");
//		BeanUtils.copy(destSysUser2, sysRole);
//		System.out.println(destSysUser2.getFdId() + "==name:"
//				+ destSysUser2.getFdName() + "==email:"
//				+ destSysUser2.getFdEmail());

	}

	/**
	 * @Author Rambo
	 * @Desc：把src赋予dest 为null的字段不复制
	 * @param destSysUser
	 * @param srcSysUser
	 *            TODO
	 * @Version BeanUtils.java,v 1.1 2013-11-21 下午3:27:12
	 */
	public static void copy(Object destSysUser, Object srcSysUser) {
		Field[] srcField = srcSysUser.getClass().getDeclaredFields();
		Class claszz = destSysUser.getClass();
		for (int n = 0; n < srcField.length; n++) {
			String srcFieldName = srcField[n].getName();
			String srcFieldType = srcField[n].getGenericType().toString();
			Object srcobj = null;
			try {
				srcField[n].setAccessible(true);
				srcobj = srcField[n].get(srcSysUser);
				Field field = claszz.getDeclaredField(srcFieldName);

				if (null != srcobj && null != field) { // 原值存在，目标字段存在
					field.setAccessible(true);
					if (srcFieldType.equals("class java.lang.String")) {// 字符串直接转化
						if (srcobj.equals(field.get(destSysUser))) {

						} else {
							field.set(destSysUser, srcobj);
							// srcField[n].set(destSysUser, srcobj);
						}
					}

				}
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SecurityException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (NoSuchFieldException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}
}
